package com.pay.container.robto;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import com.alibaba.fastjson.JSON;
import com.pay.constant.Constant;
import com.pay.container.ZfbRobtoContainer;
import com.pay.download.FundAccountDetailDownload;
import com.pay.download.ItemsDownload;
import com.pay.download.StandardDownload;
import com.pay.download.processor.FundAccountDetailProcessor;
import com.pay.download.processor.ItemsProcessor;
import com.pay.download.processor.StandardProcessor;
import com.pay.entity.ZfbInLog;
import com.pay.entity.ZfbMember;
import com.pay.resource.SpringBeanResource;

/**
 * 支付宝机器人容器
 * 每一个机器人线程
 * 机器人只可以修改下线，不可修改上线
 * @author tianpeng
 *
 */
public class ZfbRobto implements Runnable {

	private ZfbMember zfbMember ;

	public ZfbMember getZfbMember() {
		return zfbMember;
	}
	public void setZfbMember(ZfbMember zfbMember) {
		this.zfbMember = zfbMember;
	}


	@Override
	public void run() {

		CloseableHttpResponse htmlResponse=null;
		HttpGet fundAccountDetailGet = new HttpGet("https://mbillexprod.alipay.com/enterprise/tradeListQuery.htm");
		fundAccountDetailGet.addHeader("Cookie", zfbMember.getCookie());
		fundAccountDetailGet.addHeader("Origin","https://mbillexprod.alipay.com");
		fundAccountDetailGet.addHeader("Referer","https://b.alipay.com/");
		fundAccountDetailGet.addHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36 QQBrowser/4.4.116.400 Version/5.1.1 Safari/534.51.22");
		fundAccountDetailGet.addHeader("Upgrade-Insecure-Requests", "1");

		HttpGet itemsGet = new HttpGet("https://my.alipay.com/portal/i.htm");
		itemsGet.addHeader("Cookie", zfbMember.getCookie());
		itemsGet.addHeader("Referer","https://my.alipay.com/portal/i.htm");
		itemsGet.addHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36 QQBrowser/4.4.116.400 Version/5.1.1 Safari/534.51.22");
		itemsGet.addHeader("Upgrade-Insecure-Requests", "1");

		
		int j = 0 ; //表示调用接口总次数
		int count = 0 ; //失败次数
		int interfaceFlag = 2 ; //接口标记

		boolean isSleep = true ; //是否需要休眠
		while(true) {
			try {
				
				isSleep = true ; 
				if(zfbMember.getStatus() == Constant.robto_off_line) {
					//如果是离线就停止检测了
					break ; 
				}
				
				CloseableHttpClient httpClient=HttpClients.createDefault(); // 创建httpClient实例
				htmlResponse = httpClient.execute(fundAccountDetailGet) ;
				htmlResponse.close();
				httpClient.close(); //调用前置唤醒cookie
				
				httpClient=HttpClients.createDefault(); // 创建httpClient实例
				htmlResponse = httpClient.execute(itemsGet) ;
				htmlResponse.close();
				httpClient.close(); //调用前置唤醒cookie
				
				String result = "" ;
				Map<String,String> map = null ;
				switch(interfaceFlag) {
					case 0:{
						//fundAccountDetail.json 接口
						
						result = FundAccountDetailDownload.download(zfbMember) ;
						map = FundAccountDetailProcessor.processor(result,zfbMember) ;
						System.out.println(interfaceFlag);
						break ;
					}
					case 1:{
						//items接口
						
						result = ItemsDownload.download(zfbMember) ;
						map = ItemsProcessor.processor(result, zfbMember) ;
						System.out.println(interfaceFlag);
						/*map = new HashMap<>() ;
						map.put("status", "warning") ;*/
						break ;
					}
					case 2:{
						// standard接口 
						
						result = StandardDownload.download(zfbMember) ;
						map = StandardProcessor.processor(result, zfbMember) ;
						System.out.println(interfaceFlag);
						break ;
					}
				}
				
				if(interfaceFlag == 2) {
					//重置到json接口
					interfaceFlag = 0 ;
				}else {
					interfaceFlag ++ ;
				}
				
				String status = map.get("status") ;
				if("error".equals(status)) {
					//等于空的话那么就是值错误
					//修改数据库
					zfbMember.setStatus(Constant.robto_off_line);
					SpringBeanResource.zfbMemberService.updateById(zfbMember) ;
					//从容器中移除掉
					ZfbRobtoContainer.container.remove(zfbMember.getId()) ;
					//结束线程
					break ;
				}
				System.out.println(map);
				System.out.println(j ++ );
				if("warning".equals(status)) {
					//警告就是接口被限制了
					//不等于的话那么就是掉钱了还有可能是被频繁访问限制了
					if(count <= 4) {
						System.out.println("当前的失败次数是：" + count);
						System.out.println("当前的接口是" + interfaceFlag);
						count ++ ; //增加失败次数
						
						isSleep = false ;
						continue ;  //改变接口
					
					}
					//修改数据库
					zfbMember.setStatus(Constant.robto_off_line);
					SpringBeanResource.zfbMemberService.updateById(zfbMember) ;
					//从容器中移除掉
					ZfbRobtoContainer.container.remove(zfbMember.getId()) ;
					//结束线程
					
					break ;
					//全部都限制了
				}
				count = 0 ; //如果成功了就清空失败次数
				String data = map.get("data");
				List<ZfbInLog> list = JSON.parseArray(data, ZfbInLog.class);
				for (ZfbInLog zfbInLog : list) {
					SpringBeanResource.zfbInLogService.handlePay(zfbMember.getId(), zfbInLog.getTradeNo(), zfbInLog.getMoney(), zfbInLog.getFlagcode(),zfbInLog.getTransname());
				}
				
			}catch(Exception e) {
				e.printStackTrace(); 
			}finally {
				try {
					if(isSleep) {
						TimeUnit.SECONDS.sleep(66);
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				} 
			}

		}
	}

}
